package com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.waiting;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baihan.angus.app.game.basic.base.BaseFragment;
import com.baihan.angus.app.game.basic.utils.Loog;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.busshow.BR;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.adps.WaitingAreaAdp;
import com.baihan.angus.app.game.busshow.databinding.FragmentWaitingAreaBinding;
import com.baihan.angus.app.game.busshow.pop_dialog.CreateRoomDialog;
import com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.room.VoiceRoomAudienceActivity;
import com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.room.VoiceRoomDmActivity;
import com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.script_library.ScriptLibraryActivity;
import com.baihan.angus.app.game.common.bean.response.CreateRoomResponse;
import com.baihan.angus.app.game.common.bean.response.LoginResponse;
import com.baihan.angus.app.game.common.bean.response.RoomDetailResponse;
import com.baihan.angus.app.game.common.bean.response.RoomResponse;
import com.baihan.angus.app.game.common.bean.response.ScriptResponse;
import com.baihan.angus.app.game.common.bean.response.Userinfo;
import com.baihan.angus.app.game.common.model.VoiceRoomManager;
import com.tencent.imsdk.v2.V2TIMGroupInfoResult;
import com.tencent.trtc.TRTCCloudDef;

import java.util.HashMap;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * 等待区
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class WaitingAreaFragment extends BaseFragment<FragmentWaitingAreaBinding, WaitingAreaVM> {

    private static final int SELECT_SCRIPT = 0xb10;

    private Map<String, Object> mParameter = new HashMap<>();
    private Map<String, Object> mCreateRequest = new HashMap<>();
    private Map<String, Object> mEnterRequest = new HashMap<>();

    private WaitingAreaAdp mWaitingAreaAdp;

    private CreateRoomDialog mCreateRoomDialog;

    private Userinfo userInfo;
    private int mPage = 1;
    private int mSize = 10;
    private int mType = 0;
    private int totalPage = 0;
    private ScriptResponse.DataX.Data scriptResponse;
    private String sn;

    public WaitingAreaFragment() {
        // Required empty public constructor
    }

    public static WaitingAreaFragment newInstance() {
        WaitingAreaFragment fragment = new WaitingAreaFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getViewModelId() {
        return BR.waitingAreaVM;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_waiting_area;
    }

    @Override
    protected void initView() {

        mWaitingAreaAdp = new WaitingAreaAdp();
        mVDBinding.rvWaiting.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        mWaitingAreaAdp.bindToRecycleView(mVDBinding.rvWaiting);

        mVDBinding.srlWaiting.setOnRefreshListener(refreshLayout -> {
            mPage = 1;
            mParameter.put("page", mPage);
            mViewModel.getWaitingAreaRoom(mParameter);
        });

        mVDBinding.srlWaiting.setOnLoadMoreListener(refreshLayout -> {
            mParameter.put("page", ++mPage);
            mViewModel.getWaitingAreaRoom(mParameter);
        });

        mWaitingAreaAdp.setOnItemClickListener(new WaitingAreaAdp.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mEnterRequest.put("dm_user_id", mWaitingAreaAdp.getItem(position).getUser().getId());
                mEnterRequest.put("user_id", userInfo.getUser_id());
                sn = mWaitingAreaAdp.getItem(position).getSn();
                mViewModel.enterRoom(sn, mEnterRequest);
            }
        });

        mVDBinding.llQuickStart.setOnClickListener(view -> {
            if (userInfo.getType() == 0) {

            } else if (userInfo.getType() == 1) {
                if (null == mCreateRoomDialog) {
                    mCreateRoomDialog = new CreateRoomDialog(getActivity(), new CreateRoomDialog.Callback() {
                        @Override
                        public void onCreate(int reverse, int auth, String scriptId) {
                            mCreateRequest.put("reverse", reverse);
                            mCreateRequest.put("auth", auth);
                            mCreateRequest.put("script_id", scriptId);
                            mViewModel.createRoom(mCreateRequest);
                            mCreateRoomDialog.dismiss();
                        }

                        @Override
                        public void onChooseScript() {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), ScriptLibraryActivity.class);
                            startActivityForResult(intent, SELECT_SCRIPT);
                        }
                    });
                }
                mCreateRoomDialog.show();
            }
        });

    }

    @Override
    protected void initData() {
        mViewModel.getUserInfo();

        mParameter.put("page", mPage);
        mParameter.put("size", mSize);
        mParameter.put("type", mType);
        mViewModel.getWaitingAreaRoom(mParameter);
    }

    @Override
    protected void initObservers() {
        mViewModel.mldWaitingRoom.observe(this, new Observer<RoomResponse.DataX>() {
            @Override
            public void onChanged(RoomResponse.DataX dataX) {
                if (mVDBinding.srlWaiting.isRefreshing()) mVDBinding.srlWaiting.finishRefresh();
                if (mVDBinding.srlWaiting.isLoading()) mVDBinding.srlWaiting.finishLoadMore();

                if (dataX == null) return;

                if (mPage == 1) {
                    mWaitingAreaAdp.setNewData(dataX.getData());
                } else {
                    mWaitingAreaAdp.addAll(dataX.getData());
                }

                if (dataX.getTotal() % mSize > 0) {
                    totalPage = dataX.getTotal() / mSize + 1;
                } else {
                    totalPage = dataX.getTotal() / mSize;
                }

                if (mPage < totalPage) {
                    mVDBinding.srlWaiting.setEnableLoadMore(true);
                } else {
                    mVDBinding.srlWaiting.setEnableLoadMore(false);
                }
            }
        });

        mViewModel.mldCreateRoom.observe(this, new Observer<CreateRoomResponse>() {
            @Override
            public void onChanged(CreateRoomResponse createRoomResponse) {
                //获取房间信息
                mViewModel.getCreateRoomDetail(createRoomResponse.getData().getSn());
                sn = createRoomResponse.getData().getSn();
            }
        });

        mViewModel.mldCreateRoomDetail.observe(this, new Observer<RoomDetailResponse.Data>() {
            @Override
            public void onChanged(RoomDetailResponse.Data data) {
                VoiceRoomDmActivity.createRoom(getContext(), data, sn, data.getScript().getName(), data.getScript_role().size() + 1, userInfo.getId(),
                        userInfo.getNickname(), data.getScript().getCover(), TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT, true);
            }
        });

        mViewModel.mldEnterResult.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    //获取进入房间的信息
                    mViewModel.getEnterRoomDetail(sn);
                }
            }
        });

        mViewModel.mldEnterRoomDetail.observe(this, new Observer<RoomDetailResponse.Data>() {
            @Override
            public void onChanged(RoomDetailResponse.Data data) {
                enterRoom(sn, data);
            }
        });

        mViewModel.mldUser.observe(this, new Observer<LoginResponse.Data>() {
            @Override
            public void onChanged(LoginResponse.Data data) {
                if (null != data) {
                    userInfo = data.getUserinfo();

                    if (userInfo.getType() == 0) {//可否创建房间-0不可创建/1-可创建
                        mVDBinding.ivStart.setImageResource(R.mipmap.ic_rocket);
                        mVDBinding.tvStart.setText(getString(R.string.quickStart));
                    } else if (userInfo.getType() == 1) {
                        mVDBinding.ivStart.setImageResource(R.mipmap.ic_create_room);
                        mVDBinding.tvStart.setText(getString(R.string.createRoom));
                    }
                }
            }
        });
    }

    private void enterRoom(final String roomId, RoomDetailResponse.Data roomData) {
        VoiceRoomManager.getInstance().getGroupInfo(roomId, new VoiceRoomManager.GetGroupInfoCallback() {
            @Override
            public void onSuccess(V2TIMGroupInfoResult result) {
                if (isRoomExist(result)) {
                    realEnterRoom(roomId, roomData);
                } else {
                    Tooast.normalInfo(getString(R.string.roomNotExist));
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.normalInfo(msg);
            }
        });
    }

    private void realEnterRoom(String roomId, RoomDetailResponse.Data roomData) {
        String userId = userInfo.getId();
//        ARouter.getInstance().build(ArouterAppPath.VOICE_ROOM_AUDIENCE_ACTIVITY)
//                .withString("roomId", roomIdStr)
//                .withString("userId", userId)
//                .withInt("audio_quality", TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT)
//                .navigation();
        VoiceRoomAudienceActivity.enterRoom(getActivity(), roomData, roomId, userId, TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
    }

    private boolean isRoomExist(V2TIMGroupInfoResult result) {
        if (result == null) {
            Loog.e(getString(R.string.roomNotExist));
            return false;
        }
        return result.getResultCode() == 0;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_SCRIPT) {
            if (resultCode == RESULT_OK) {
                scriptResponse = (ScriptResponse.DataX.Data) data.getSerializableExtra("scriptItem");
//                scriptId = data.getStringExtra("scriptId");
//                scriptName = data.getStringExtra("scriptName");
                mCreateRoomDialog.setData(scriptResponse.getName(), scriptResponse.getScript_id());
            }
        }
    }

    @Override
    protected void onVisibleAgain() {
        super.onVisibleAgain();
        mVDBinding.srlWaiting.autoRefresh();
    }
}